import 'dart:async';

import 'package:get/get.dart';

class CountdownController extends GetxController {
  // 倒计时剩余时间（秒）
  final RxInt _remainingSeconds = 60.obs;
  final RxBool _isComplete = true.obs;

  int get remainingSeconds => _remainingSeconds.value;

  bool get isComplete => _isComplete.value;

  // 定时器
  Timer? _timer;

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    _stopTimer();
    super.onClose();
  }

  // 时间格式化显示（00:00）
  String get formattedTime {
    final minutes = (remainingSeconds ~/ 60).toString().padLeft(2, '0');
    final seconds = (remainingSeconds % 60).toString().padLeft(2, '0');
    return '$minutes:$seconds';
  }

  // 开始倒计时
  void start() {
    if (_timer != null && _timer!.isActive) return;

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      _isComplete.value = false;

      if (_remainingSeconds > 0) {
        _remainingSeconds.value--;
      } else {
        _stopTimer();
      }
    });
  }

  void setInitialTime(int seconds) {
    reset();
    _remainingSeconds.value = seconds;
  }

  // 暂停倒计时
  void pause() => _stopTimer();

  // 重置倒计时
  void reset() {
    _stopTimer();
    _remainingSeconds.value = 60;
  }

  // 停止定时器
  void _stopTimer() {
    _isComplete.value = true;
    _timer?.cancel();
    _timer = null;
  }
}
